package org.lanqiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lanqiao.common.CustomException;
import org.lanqiao.dto.SetmealDto;
import org.lanqiao.entity.Setmeal;
import org.lanqiao.entity.SetmealDish;
import org.lanqiao.mapper.SetmealMapper;
import org.lanqiao.service.SetmealDishService;
import org.lanqiao.service.SetmealService;
import org.lanqiao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存setmealDto中的套餐信息到setmeal表中
        this.save(setmealDto);

        //获取套餐id
        Long id = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
        }

        //套餐菜品关系表中添加数据
        setmealDishService.saveBatch(setmealDishes);
    }


    @Override
    @Transactional
    public void deleteSetmealAndSetmealDish(List<Long> ids) {

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        //查找id在ids中的
        queryWrapper.in("id" , ids);
        //查找状态为停售（启售的不能删除）
        queryWrapper.eq("status" , 1);

        //查找满足条件的套餐的数量
        int count = this.count(queryWrapper);

        if(count > 0){
            throw new CustomException("套餐正在售卖中，无法删除");
        }
        //删除setmeal表中该套餐相关信息
        this.removeByIds(ids);

        QueryWrapper<SetmealDish> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("setmeal_id" , ids);

        setmealDishService.remove(queryWrapper1);

    }
}
